package my.diplom.web.validators;

import org.springframework.validation.Validator;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import my.diplom.entity.Resource;
import my.diplom.entity.Host;

import java.util.regex.Pattern;

/**
 * Created by IntelliJ IDEA.
 * User: gb
 * Date: 04.11.2009
 * Time: 3:33:11
 * To change this template use File | Settings | File Templates.
 */
public class CreateHostValidator implements Validator {

    public boolean supports(Class clazz) {
        return Host.class.equals(clazz);
    }

    @Override
    public void validate(Object o, Errors errors) {
        Host host = (Host) o;
        if (host == null) errors.reject("Null data received");

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "hostName", "hostName.empty", "host Name is required");
        if (host.getHostName().length() > 250) errors.rejectValue("hostName", "lenght is too long!");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "ipAddress", "ipAddress.empty", "ip address is required");
        if (!isValidAddress(host.getIpAddress())) errors.rejectValue("ipAddress", "ip.wrong", "address is wrong!");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "cpu", "cpu.empty", "PCU is required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "hdd", "hdd.empty", "HDD is required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "ram", "ram.empty", "RAM is required");


    }

    private boolean isValidAddress(String address){
        Pattern pattern =
        Pattern.compile("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b");
        return pattern.matcher(address).matches();
    }

}
